<template>
  <div class="linkage-rule-editor">
    <div class="editor-header">
      <h3>联动规则配置</h3>
      <div class="header-actions">
        <Button type="primary" @click="saveRule" :loading="saving">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存
        </Button>
        <Button @click="$emit('cancel')">
          <IconifyIcon icon="ant-design:close-outlined" />
          取消
        </Button>
      </div>
    </div>

    <div class="editor-content">
      <Form
        :model="ruleData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        layout="horizontal"
      >
        <!-- 基本信息 -->
        <div class="section">
          <h4>基本信息</h4>
          <FormItem label="规则名称" name="name">
            <Input v-model:value="ruleData.name" placeholder="请输入规则名称" />
          </FormItem>

          <FormItem label="规则描述" name="description">
            <Input.TextArea
              v-model:value="ruleData.description"
              placeholder="请输入规则描述"
              :rows="3"
            />
          </FormItem>

          <FormItem label="是否启用" name="enabled">
            <Switch v-model:checked="ruleData.enabled" />
          </FormItem>
        </div>

        <!-- 触发条件 -->
        <div class="section">
          <h4>触发条件</h4>
          <div class="condition-builder">
            <div
              v-for="(condition, index) in ruleData.conditions"
              :key="index"
              class="condition-item"
            >
              <Row :gutter="16">
                <Col :span="8">
                  <FormItem :label="index === 0 ? '字段' : ''">
                    <Select
                      v-model:value="condition.field"
                      placeholder="选择字段"
                      @change="onConditionFieldChange(index)"
                    >
                      <SelectOption
                        v-for="field in availableFields"
                        :key="field.name"
                        :value="field.name"
                      >
                        {{ field.label }}
                      </SelectOption>
                    </Select>
                  </FormItem>
                </Col>
                <Col :span="6">
                  <FormItem :label="index === 0 ? '操作符' : ''">
                    <Select
                      v-model:value="condition.operator"
                      placeholder="选择操作符"
                    >
                      <SelectOption value="=">等于</SelectOption>
                      <SelectOption value="!=">不等于</SelectOption>
                      <SelectOption value=">">大于</SelectOption>
                      <SelectOption value=">=">大于等于</SelectOption>
                      <SelectOption value="<">小于</SelectOption>
                      <SelectOption value="<=">小于等于</SelectOption>
                      <SelectOption value="contains">包含</SelectOption>
                      <SelectOption value="startsWith">开头是</SelectOption>
                      <SelectOption value="endsWith">结尾是</SelectOption>
                    </Select>
                  </FormItem>
                </Col>
                <Col :span="8">
                  <FormItem :label="index === 0 ? '值' : ''">
                    <Input
                      v-model:value="condition.value"
                      placeholder="输入值"
                    />
                  </FormItem>
                </Col>
                <Col :span="2">
                  <FormItem :label="index === 0 ? '操作' : ''">
                    <Button type="text" danger @click="removeCondition(index)">
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </Button>
                  </FormItem>
                </Col>
              </Row>
            </div>
            <Button type="dashed" @click="addCondition">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加条件
            </Button>
          </div>
        </div>

        <!-- 执行动作 -->
        <div class="section">
          <h4>执行动作</h4>
          <div class="action-builder">
            <div
              v-for="(action, index) in ruleData.actions"
              :key="index"
              class="action-item"
            >
              <Row :gutter="16">
                <Col :span="6">
                  <FormItem :label="index === 0 ? '动作类型' : ''">
                    <Select
                      v-model:value="action.type"
                      placeholder="选择动作类型"
                      @change="onActionTypeChange(index)"
                    >
                      <SelectOption value="UPDATE">更新字段</SelectOption>
                      <SelectOption value="SHOW">显示字段</SelectOption>
                      <SelectOption value="HIDE">隐藏字段</SelectOption>
                      <SelectOption value="DISABLE">禁用字段</SelectOption>
                      <SelectOption value="ENABLE">启用字段</SelectOption>
                      <SelectOption value="SET_VALUE">设置值</SelectOption>
                      <SelectOption value="CLEAR_VALUE">清空值</SelectOption>
                    </Select>
                  </FormItem>
                </Col>
                <Col :span="6">
                  <FormItem :label="index === 0 ? '目标字段' : ''">
                    <Select
                      v-model:value="action.targetField"
                      placeholder="选择目标字段"
                    >
                      <SelectOption
                        v-for="field in availableFields"
                        :key="field.name"
                        :value="field.name"
                      >
                        {{ field.label }}
                      </SelectOption>
                    </Select>
                  </FormItem>
                </Col>
                <Col :span="8">
                  <FormItem :label="index === 0 ? '参数' : ''">
                    <Input
                      v-model:value="action.parameter"
                      placeholder="输入参数值"
                    />
                  </FormItem>
                </Col>
                <Col :span="4">
                  <FormItem :label="index === 0 ? '操作' : ''">
                    <Button type="text" danger @click="removeAction(index)">
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </Button>
                  </FormItem>
                </Col>
              </Row>
            </div>
            <Button type="dashed" @click="addAction">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加动作
            </Button>
          </div>
        </div>

        <!-- 高级配置 -->
        <div class="section">
          <h4>高级配置</h4>
          <FormItem label="执行延迟" name="delay">
            <InputNumber
              v-model:value="ruleData.delay"
              :min="0"
              placeholder="延迟执行时间(毫秒)"
              style="width: 100%"
            />
          </FormItem>

          <FormItem label="执行次数" name="maxExecutions">
            <InputNumber
              v-model:value="ruleData.maxExecutions"
              :min="1"
              placeholder="最大执行次数"
              style="width: 100%"
            />
          </FormItem>

          <FormItem label="错误处理" name="errorHandling">
            <Select
              v-model:value="ruleData.errorHandling"
              placeholder="选择错误处理方式"
            >
              <SelectOption value="IGNORE">忽略错误</SelectOption>
              <SelectOption value="STOP">停止执行</SelectOption>
              <SelectOption value="RETRY">重试执行</SelectOption>
            </Select>
          </FormItem>
        </div>
      </Form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue';
import {
  Form,
  FormItem,
  Input,
  Select,
  SelectOption,
  Switch,
  InputNumber,
  Button,
  Row,
  Col,
  message,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
const props = defineProps<{
  rule: any;
  fields: any[];
}>();

// Emits
const emit = defineEmits<{
  update: [rule: any];
  cancel: [];
}>();

// 响应式数据
const saving = ref(false);
const ruleData = reactive({
  id: '',
  name: '',
  description: '',
  enabled: true,
  conditions: [],
  actions: [],
  delay: 0,
  maxExecutions: 1,
  errorHandling: 'IGNORE',
});

// 计算属性
const availableFields = computed(() => {
  return props.fields.filter((field) => field.name && field.label);
});

// 监听props变化
watch(
  () => props.rule,
  (newRule) => {
    if (newRule) {
      Object.assign(ruleData, {
        id: newRule.id || '',
        name: newRule.name || '',
        description: newRule.description || '',
        enabled: newRule.enabled !== false,
        conditions: newRule.conditions || [],
        actions: newRule.actions || [],
        delay: newRule.delay || 0,
        maxExecutions: newRule.maxExecutions || 1,
        errorHandling: newRule.errorHandling || 'IGNORE',
      });
    }
  },
  { immediate: true, deep: true },
);

// 方法
const addCondition = () => {
  ruleData.conditions.push({
    field: '',
    operator: '=',
    value: '',
  });
};

const removeCondition = (index: number) => {
  ruleData.conditions.splice(index, 1);
};

const onConditionFieldChange = (index: number) => {
  // 根据字段类型调整操作符选项
  const condition = ruleData.conditions[index];
  const field = availableFields.value.find((f) => f.name === condition.field);

  if (field) {
    // 根据字段类型设置合适的默认操作符
    if (field.type === 'NUMBER') {
      condition.operator =
        condition.operator === 'contains' ? '=' : condition.operator;
      condition.operatorcondition.operator;
    } else if (field.type === 'STRING') {
      condition.operator =
        condition.operator === '>' ? '=' : condition.operator;
      condition.operatorcondition.operator;
    }
  }
};

const addAction = () => {
  ruleData.actions.push({
    type: 'UPDATE',
    targetField: '',
    parameter: '',
  });
};

const removeAction = (index: number) => {
  ruleData.actions.splice(index, 1);
};

const onActionTypeChange = (index: number) => {
  const action = ruleData.actions[index];

  // 根据动作类型设置默认参数
  switch (action.type) {
    case 'SHOW':
    case 'HIDE':
    case 'DISABLE':
    case 'ENABLE':
      action.parameter = '';
      break;
    case 'SET_VALUE':
      action.parameter = '';
      break;
    case 'CLEAR_VALUE':
      action.parameter = '';
      break;
  }
};

const saveRule = async () => {
  // 验证必填字段
  if (!ruleData.name) {
    message.error('请输入规则名称');
    return;
  }

  if (ruleData.conditions.length === 0) {
    message.error('请至少添加一个触发条件');
    return;
  }

  if (ruleData.actions.length === 0) {
    message.error('请至少添加一个执行动作');
    return;
  }

  // 验证条件
  for (const condition of ruleData.conditions) {
    if (!condition.field || !condition.operator) {
      message.error('请完善触发条件配置');
      return;
    }
  }

  // 验证动作
  for (const action of ruleData.actions) {
    if (!action.type || !action.targetField) {
      message.error('请完善执行动作配置');
      return;
    }
  }

  saving.value = true;
  try {
    // 模拟保存
    await new Promise((resolve) => setTimeout(resolve, 500));

    const updatedRule = { ...ruleData };
    emit('update', updatedRule);
    message.success('联动规则保存成功');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};
</script>

<style lang="less" scoped>
.linkage-rule-editor {
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .editor-content {
    .section {
      margin-bottom: 32px;

      h4 {
        margin: 0 0 16px 0;
        font-size: 14px;
        font-weight: 600;
        color: #333;
        padding-left: 8px;
        border-left: 3px solid #1890ff;
      }
    }

    .condition-builder,
    .action-builder {
      .condition-item,
      .action-item {
        border: 1px solid #f0f0f0;
        border-radius: 6px;
        padding: 16px;
        margin-bottom: 12px;
        background: #fafafa;
      }
    }
  }
}
</style>
